<template>
  <header class="main-header container">
    <div class="fr-w header-box">
      <div class="header-left">
        <!-- 菜单栏log -->
        <!-- <img :src="logoLink"> -->
        <span class="title">销管系统-直销</span>
      </div>
      <div class="header-right">
        <slot name="notify" />
        <span v-if="ifshow == '0'" class="inspect-code">
          今日验车码：
          <span class="inspect-code-ctn">{{ inspectCode }}</span>
        </span>
        <span>
          欢迎您 :
          <el-dropdown @command="handleCommand">
            <span class="el-dropdown-link nor-btn">
              {{ nowdept }}
              <i class="el-icon-caret-bottom el-icon--right" />
            </span>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item
                v-for="(item, index) in depts"
                :key="index"
                :command="item.c_oper_dept_code"
              >{{ item.c_oper_dept_code }}-{{ item.c_oper_dept_name }}</el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </span>
        <span class="nor-btn" @click="clickUser" v-text="nowuser" />
        <span>现在是：</span>
        <span v-text="nowdate" />
        <!-- <span class="nor-btn" @click="editpwd">修改密码</span> -->
        <span class="nor-btn" @click="clearCacheSys">清空缓存</span>
        <span class="nor-btn" @click="passwordDialog=true">修改密码</span>
        <!-- <span class="nor-btn" @click="drawer=true">修改密码</span> -->
        <span class="nor-btn" @click="logout">退出</span>
      </div>
      <!-- <div class="user-info">
        <el-drawer
          ref="drawer"
          title="修改密码"
          :modal="false"
          :wrapper-closable="false"
          :before-close="handleClose"
          :visible.sync="drawer"
          direction="rtl"
          custom-class="user-drawer"
        >
          <div class="user-drawer__content">
            <el-form ref="userForm" :model="currentOper" :rules="userRule">
              <el-form-item label="新密码" prop="c_psswd" :label-width="formLabelWidth">
                <el-input v-model="currentOper.c_psswd" type="password" autocomplete="off" />
              </el-form-item>
              <el-form-item label="确认密码" prop="c_new_psswd" :label-width="formLabelWidth">
                <el-input v-model="currentOper.c_new_psswd" type="password" autocomplete="off" />
              </el-form-item>
              <el-form-item :label-width="formLabelWidth">
                <div class="user-drawer__footer" style="margin-top: 20px;">
                  <el-button @click="cancelForm">
                    取 消
                  </el-button>
                  <el-button type="primary" :loading="loading" @click="save">
                    {{ loading ? '提交中 ...' : '确 定' }}
                  </el-button>
                </div>
              </el-form-item>
            </el-form>
          </div>
        </el-drawer>
      </div> -->
      <PwdReset
        :dialog-visible="passwordDialog" :as="args" :is-show-close="true"
        @close="passwordDialog = false"
      />
    </div>
  </header>
</template>
<script>
import { cacheUtil, util } from 'utils/util'; // 缓存工具类
import { sessionCache, localCache, clear } from 'src/store/cache-util.js';
import merge from 'utils/merge';
import { getMenu } from 'src/api/user';
import { getOper } from '@/modules/index/src/common/tools';
import PwdReset from '@/modules/exportUm/reset/reset.vue';
import { isNull } from '@/modules/index/src/common/tools';
import { post } from 'utils/util';
export default {
  name: 'MainHeader',
  components: {
		PwdReset
	},
  props: {
    nowuser: { type: String, default: '匿名' },
    nowdate: { type: String, default: '0000-000-000' },
    nowdept: { type: String, default: '' },
    nowdeptCode: { type: String, default: '' },
    logoLink: {
      type: String,
      default: 'static/img/logo.png'
    },
    depts: {
      type: Array,
      default: function() {
        return [];
      }
    },
    editpwd: {
      type: Function,
      default: function() {
        const fn = new Function();
        return fn;
      }
    },
    logout: {
      type: Function,
      default: function() {
        const fn = new Function();
        return fn;
      }
    },
    clearCache: {
      type: Function,
      default: function() {
        const fn = new Function();
        return fn;
      }
    },
    clickUser: {
      type: Function,
      default: function() {
        const fn = new Function();
        return fn;
      }
    }
  },
  data() {
    const checkCardNo = (rule, value, callback) => {
      const exp = /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/;
      // 为空不校验
      if (value === '') {
        callback();
      }
      if (!exp.test(value)) {
        callback(new Error('请输入合法的身份证号'));
      } else {
        callback();
      }
    };
    const checkmobileNo = (rule, value, callback) => {
      const exp = /(^0{0,1}1[3|4|5|6|7|8|9][0-9]{9}$)/;
      // 为空不校验
      if (value === '') {
        callback();
      }
      if (!exp.test(value)) {
        callback(new Error('请输入合法的手机号'));
      } else {
        callback();
      }
    };
    const validatePass2 = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请再次输入密码'));
      } else if (value !== this.currentOper.c_psswd) {
        callback(new Error('两次输入密码不一致!'));
      } else {
        callback();
      }
    };
    return {
			passwordDialog: false,
      ifshow: '1',
			args: {},
      // 是否是当前页
      isCurPage: false,
      // 抽屉开关
      drawer: false,
      loading: false,
      currentOper: {
        // c_cert_no: '',
        // c_email: '',
        // c_mobile_no: '',
				// c_surepwd: '',
        c_psswd: '',
        c_new_psswd: '',
				c_oper_code: getOper().c_oper_code
      },
      oldOper: {
        c_cert_no: '',
        c_email: '',
        c_psswd: '',
        c_mobile_no: '',
        c_new_psswd: ''
      },

      formLabelWidth: '80px',
      timer: null,
      userRule: {
        c_mobile_no: [
          {
            required: false,
            validator: checkmobileNo,
            trigger: 'blur'
          }
        ],
        c_cert_no: [
          {
            required: false,
            validator: checkCardNo,
            trigger: 'blur'
          }
        ],
				c_psswd: [
					{
						required: true,
						message: '请输入密码',
						trigger: 'blur'
					}
				],
				c_new_psswd: [
					{
						required: true,
						message: '请输入新密码',
						trigger: 'blur'
					},
					{
            validator: validatePass2,
            trigger: 'blur'
          },
					{
            pattern: /^(?![a-zA-Z]+$)(?![A-Z0-9]+$)(?![A-Z!@#$%^&*()_+]+$)(?![a-z0-9]+$)(?![a-z!@#$%^&*()_+]+$)(?![0-9!@#$%^&*()_+]+$)[a-zA-Z0-9!@#$%^&*()_+]{8,30}$/,
            message: '密码至少8位，包含大写字母、小写字母、数字、特殊字符(!@#$%^&*()_+)这四种组合中的至少三种组合',
            trigger: 'blur'
          }
				]
      }
    };
  },
  computed: {
    inspectCode() {
      return this.$store.getters['codeStore/getInspectCode'];
    }
  },
  mounted() {
    window.addEventListener('storage', this.listenStorage);
		const id = this.getUrlParam('id');
    let token = ''; let userId = ''; let from = '';
    if (!id) {
      const oper = JSON.parse(cacheUtil.getCookies('oper'));
      from = this.getUrlParam('from') || '';
      if (oper) {
        userId = oper.c_oper_code || '';
      }
      token = cacheUtil.getCookies('Authorization') || '';
    }
		this.args = {
			ID: id,
			UserId: userId,
			Token: token,
			From: from
		};
  },
  destroyed() {
    window.removeEventListener('storage', this.listenStorage);
  },
  created() {
    getMenu(
      {},
      res => {
        const data = res.data.data;
        for (let i = 0; i < data.length; i++) {
          if (data[i].code === '11') {
            // 判断该用户是否存在车承保菜单权限，如果存在在portal-web头部调用获取验车码的请求拿到今日验车码
            this.ifshow = '0';
            this.getInspectCode();
          }
        }
      },
      error => {
        console.error(error);
      }
    );
  },
  methods: {
		getUrlParam(name) {
			const reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)');
			const str = window.location.search;
			let r = '';
			if (str.substring(0, 4) === '?id=') {
				r = str.substr(1).match(reg);
			} else {
				r = decodeURIComponent(window.atob(str.substr(1))).match(reg);
			}
			if (r != null) return unescape(r[2]); return null;
		},
    clearCacheSys() {
      // 清除缓存
      clear(localCache);
      clear(sessionCache);
      if (window.localStorage.length <= 0 && window.sessionStorage.length <= 0) {
        this.$message.success('缓存清除成功');
      } else {
        this.$message.error('缓存清除失败');
      }
    },
    handleCommand(command, instance) {
      if (command !== this.nowdeptCode) {
        // this.$emit('deptchange', command, instance);
        util.changeDept(command);
        this.isCurPage = true;
      }
    },
    // 监听localStorage数据变化
    listenStorage(e) {
      if (e.key === 'changeDeptCode' && e.newValue) {
        if (!this.isCurPage) {
          // 刷新当前页面
          window.location.reload();
        } else {
          this.isCurPage = false;
        }
      }
    },
    rootReload() {
      this.$root.reload();
    },

    handleClose(done) {
      if (this.loading) {
        return;
      }
      // 校验表单有没有被修改
      const isEqual = this.validateFrom();
      console.log('校验结果', isEqual);
      if (!isEqual) {
        this.$confirm('内容已修改但没保存,确定要关闭吗？')
          .then(_ => {
            // this.loading = true;
            // this.timer = setTimeout(() => {
            //   //done();
            //   // 动画关闭需要一定的时间
            //   setTimeout(() => {
            //     this.loading = false;
            //   }, 400);
            // }, 2000);
            this.cancelForm();
          })
          .catch(_ => {});
      } else {
        this.cancelForm();
      }
    },
    // 取消操作
    cancelForm() {
      this.loading = false;
      this.drawer = false;
      clearTimeout(this.timer);
    },
    // 校验表单有没有被修改
    validateFrom() {
      const oldOper = merge({}, this.oldOper);
      const currentOper = merge({}, this.currentOper);

      return this.isObjectValueEqual(oldOper, currentOper);
    },
    // 判断两个对象是否相等
    isObjectValueEqual(a, b) {
      var aProps = Object.getOwnPropertyNames(a);
      var bProps = Object.getOwnPropertyNames(b);
      if (aProps.length !== bProps.length) {
        return false;
      }
      for (var i = 0; i < aProps.length; i++) {
        var propName = aProps[i];

        var propA = a[propName];
        var propB = b[propName];
        if (propA !== propB) {
          return false;
        }
      }
      return true;
    },
    // 保存
    save() {
      this.$refs.userForm.validate(valid => {
        if (valid) {
          const that = this;
          // const currentOper = merge({}, this.currentOper);
          // // const c_new_psswd = currentOper.c_new_psswd;
          // // if (c_new_psswd) {
          // //   currentOper.c_psswd = c_new_psswd;
          // // }
					const currentOper = {
						c_psswd: this.currentOper.c_psswd,
						c_oper_code: this.currentOper.c_oper_code
					};
          const data = {
            oper: currentOper
          };
					post(SERVICE_URL + '/oper/update_oper_pwd_code',
					data,
					res => {
						if (res.errorCode === '0' && res.status === 'S') {
							Message.success({ message: '修改成功', duration: 2000 });
							that.logout();
						}
						console.log('res', res);
					},
					err => {
						Message.error({ message: err.message, duration: 2000 });
					});
          // util.request({
          //   model: data,
          //   tranCode: 'Um04010003',
          //   serviceId: '29040003',
          //   onSuccess: function(jqXHR, textStatus, data) {
          //     Message.success('修改成功');
          //     that.cancelForm();
          //     if (c_new_psswd) {
          //       // 如果修改了密码就要退出登录
          //       that.logout();
          //     }
          //   },
          //   onError: function(jqXHR, textStatus, data) {
          //     Message.error({
          //       duration: 0,
          //       message: data.message,
          //       showClose: true
          //     });
          //   }
          // });
        }
      });
    },

    // 查询方法
    query(c_oper_code) {
      const that = this;
      const eles = {
        c_oper_code: c_oper_code
      };
      util.request({
        model: eles, // 输入接口如果是对象就需要用对象封装，如果不是 就直接写vm.eles
        pageNo: 1,
        pageSize: 10,
        tranCode: 'Um05010011',
        // serviceId : "29040002",
        onSuccess: function(jqXHR, textStatus, data) {
          that.currentOper = data.model.eles;
          that.currentOper.c_new_psswd = '';
          that.oldOper = merge({}, that.currentOper);
          that.drawer = true;
        },
        onError: function(jqXHR, textStatus, data) {
          Message.error({
            duration: 0,
            message: data.message,
            showClose: true
          });
        }
      });
    },
    // 保存数据
    getInspectCode() {
      util.request({
        tranCode: 'UAUTO00100',
        showLoading: false,
        onSuccess: (jqXHR, textStatus, data) => {
          this.$store.commit('codeStore/updateInspectCode', data.model.c_carinspect_code);
        },
        onError: (jqXHR, textStatus, data) => {
          // 失败时回调
          Message.error({
            duration: 0,
            message: data.message,
            showClose: true
          });
        }
      });
    }
  }
};
</script>

<style lang="scss" scoped>
/deep/ .el-dropdown-menu {
  padding: 0;
  margin: 0 0 5px 0;
}
/deep/ .el-dropdown-menu li {
  line-height: 28px;
  height: 28px;
}
.user-info {
  /deep/ .el-drawer.ltr,
  /deep/ .el-drawer.rtl {
    width: 30% !important;
    height: 380px;
    top: 40px;
    min-width: 320px;
  }
}
.user-drawer {
  font-size: 13px;
  .el-drawer__header {
    height: 45px;
  }
  .user-drawer__content {
    font-size: 14px;
    height: 100%;
    padding: 20px;
    /deep/.el-form-item {
      height: 40px;
      line-height: 40px;
      margin-bottom: 22px;
      .el-form-item__label {
        height: 40px;
        line-height: 32px;
      }
      .el-input__inner {
        height: 40px;
        line-height: 40px;
      }
    }
  }
  .user-drawer__footer {
    width: 100%;
    display: flex;
    justify-content: space-between;

    .el-button {
      flex: 1;
      height: 40px;
    }
  }
}
// 验车码
.inspect-code {
  font-size: 14px;
  font-weight: bold;
  margin-right: 20px;

  .inspect-code-ctn {
    color: #fd696a;
  }
}
.header-left {
	.title {
		font-size: 16px;
		font-weight: 700;
		height: 40px;
		line-height: 40px;
		color: black;
	}
}
</style>
